package cn.wolfcode.cms.service.impl;

import cn.wolfcode.cms.annotation.PermissionName;
import cn.wolfcode.cms.domain.Permission;
import cn.wolfcode.cms.mapper.PermissionMapper;
import cn.wolfcode.cms.query.QueryObject;
import cn.wolfcode.cms.service.IPermissionService;
import cn.wolfcode.cms.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {

    //请求映射处理映射器
    //容器启动时候,解析RequestMapping注解, 将所有贴有这个标签的方法,封装成这个对象
    @Autowired(required = false)
    private RequestMappingHandlerMapping rmhm;



    @Autowired
    private PermissionMapper permissionMapper;

    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    public List<Permission> list() {
        return permissionMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = permissionMapper.queryForCount(qo);
        if(total == 0){
            return new PageResult();
        }
        List<Permission> rows = permissionMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    //权限加载
    public void reload() {
        //1:获取所有的权限表达式
        List<Permission> list = permissionMapper.selectAll();
        Set<String> rs = new HashSet<>();
        for (Permission permission : list) {
            rs.add(permission.getResource());
        }
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        for (HandlerMethod value : values) {

            //4:遍历所有方法, 然后判断是否拥有贴有RequiresPermissions
            RequiresPermissions ann = value.getMethodAnnotation(RequiresPermissions.class);
            if(ann != null){
                //5:解析RequiresPermissions标签, 获取权限表达式, 然后封装对象
                //权限表达式
                String resource = ann.value()[0];
                if(rs.contains(resource)){
                    continue;
                }
                String name = value.getMethodAnnotation(PermissionName.class).value();

                Permission p = new Permission();
                p.setName(name);
                p.setResource(resource);
                //6:保存对象
                permissionMapper.insert(p);
            }
        }
    }

    //通过角色id获取权限
    public List<Permission> getPermissionByRoleId(Long id) {
        return permissionMapper.getPermissionByRoleId(id);
    }

    public List<String> getPermissionResourcesByEmpId(Long id) {
        return permissionMapper.getPermissionResourcesByEmpId(id);
    }


}
